#include "PacketQueue.h"

void PacketQueue::push(AVPacket* pkt)
{
	if (!pkt)
		return;

	m_mutex.lock();

	m_q.push(pkt);
	m_bytesSize = m_bytesSize + pkt->size + sizeof(AVPacket);

	m_mutex.unlock();
}

AVPacket* PacketQueue::pop()
{
	std::lock_guard<std::mutex> lock(m_mutex);

	if (m_q.size() == 0)
		return nullptr;

	auto pkt = m_q.front();
	m_q.pop();

	m_bytesSize = m_bytesSize - (pkt->size + sizeof(AVPacket));

	return pkt;
}

int PacketQueue::queueSize()
{
	std::lock_guard<std::mutex> lock(m_mutex);
	return m_q.size();
}

size_t PacketQueue::bytesSize()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_bytesSize;
}

void PacketQueue::clear()
{
    m_mutex.lock();
    while(!m_q.empty()) {
        auto pkt = m_q.front();
        av_packet_free(&pkt);
        m_q.pop();
    }

    m_bytesSize = 0;
    m_mutex.unlock();
}


PacketQueue::~PacketQueue()
{
	std::lock_guard<std::mutex> lock(m_mutex);
	while (!m_q.empty()) {
		AVPacket* pkt = m_q.front();
		m_q.pop();
		av_packet_free(&pkt);
	}
}
